<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Modal from '../components/Modal.vue'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const error = ref('')
const preview = ref(null)
const selectedPayment = ref('alipay') // 默认选择支付宝
const modalVisible = ref(false)
const modalMessage = ref('')
const modalTitle = ref('提示')
const currentOrder = ref({
  orderNo: route.query.order_no || '',
  status: null
})

const DEFAULT_PAYMENT_MINUTES = 15
const countdownSeconds = ref(DEFAULT_PAYMENT_MINUTES * 60)
let countdownTimer = null

const parseDeadlineInput = (value) => {
  if (value === undefined || value === null || value === '') return null
  if (value instanceof Date && !Number.isNaN(value.getTime())) return value

  if (typeof value === 'number' && Number.isFinite(value)) {
    return new Date(value > 1e12 ? value : value * 1000)
  }

  if (typeof value === 'string') {
    const trimmed = value.trim()
    if (!trimmed) return null
    const numeric = Number(trimmed)
    if (!Number.isNaN(numeric)) {
      return new Date(numeric > 1e12 ? numeric : numeric * 1000)
    }
    const parsed = new Date(trimmed)
    if (!Number.isNaN(parsed.getTime())) return parsed
  }

  return null
}

const parsePositiveNumber = (value) => {
  const num = Number(value)
  return Number.isFinite(num) && num > 0 ? num : null
}

const clearCountdown = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
}

const startCountdown = (deadline) => {
  if (!(deadline instanceof Date) || Number.isNaN(deadline.getTime())) return

  clearCountdown()

  const tick = () => {
    const diff = Math.floor((deadline.getTime() - Date.now()) / 1000)
    countdownSeconds.value = diff > 0 ? diff : 0

    if (diff <= 0) {
      clearCountdown()
    }
  }

  tick()
  countdownTimer = window.setInterval(tick, 1000)
}

const initializeCountdown = (payload = null) => {
  const deadlineCandidates = [
    route.query.payment_deadline,
    route.query.deadline,
    route.query.expire_time,
    payload?.payment_deadline,
    payload?.payment_deadline_time,
    payload?.payment_deadline_at,
    payload?.expire_time
  ]

  let deadline = null
  for (const candidate of deadlineCandidates) {
    const parsed = parseDeadlineInput(candidate)
    if (parsed) {
      deadline = parsed
      break
    }
  }

  if (!deadline) {
    const baseCandidates = [
      parseDeadlineInput(route.query.created_at),
      parseDeadlineInput(payload?.created_at),
      parseDeadlineInput(payload?.order_created_at)
    ]
    const baseTime = baseCandidates.find((item) => item) || new Date()

    const expireSeconds = [
      parsePositiveNumber(route.query.expire_seconds),
      parsePositiveNumber(payload?.expire_seconds),
      parsePositiveNumber(payload?.payment_expire_seconds)
    ].find((item) => item)

    if (expireSeconds) {
      deadline = new Date(baseTime.getTime() + expireSeconds * 1000)
    } else {
      const expireMinutes =
        parsePositiveNumber(route.query.expire_minutes) ||
        parsePositiveNumber(payload?.expire_minutes)
      if (expireMinutes) {
        deadline = new Date(baseTime.getTime() + expireMinutes * 60 * 1000)
      }
    }
  }

  if (!deadline) {
    deadline = new Date(Date.now() + DEFAULT_PAYMENT_MINUTES * 60 * 1000)
  }

  startCountdown(deadline)
}

const countdownText = computed(() => {
  const seconds = Math.max(countdownSeconds.value, 0)
  const minutes = Math.floor(seconds / 60)
  const remainSeconds = seconds % 60
  return `${minutes.toString().padStart(2, '0')}:${remainSeconds.toString().padStart(2, '0')}`
})

const isCountdownExpired = computed(() => countdownSeconds.value <= 0)

const queryParams = computed(() => ({
  hotel_id: route.query.hotel_id,
  room_type_id: route.query.room_type_id,
  check_in_date: route.query.check_in_date,
  check_out_date: route.query.check_out_date,
  rooms: Number(route.query.rooms || 1)
}))

const guestName = computed(
  () => (typeof route.query.guest_name === 'string' ? route.query.guest_name : '').trim()
)

const guestPhone = computed(
  () => (typeof route.query.phone === 'string' ? route.query.phone : '').trim()
)

const hasPreviewParams = computed(
  () =>
    Boolean(
      queryParams.value.hotel_id &&
        queryParams.value.room_type_id &&
        queryParams.value.check_in_date &&
        queryParams.value.check_out_date
    )
)

let creatingOrderPromise = null

const buildOrderCreationPayload = (payableAmount) => ({
  user_id: localStorage.getItem('user_id') || 'demo-user',
  hotel_id: queryParams.value.hotel_id,
  room_type_id: queryParams.value.room_type_id,
  check_in_date: queryParams.value.check_in_date,
  check_out_date: queryParams.value.check_out_date,
  rooms: queryParams.value.rooms,
  amount: payableAmount
})

const ensureOrderCreated = async (previewPayload = null, payableOverride = null) => {
  if (currentOrder.value.orderNo) return { success: true }
  if (creatingOrderPromise) return creatingOrderPromise

  const promise = (async () => {
    const payableAmount =
      payableOverride ??
      Number(previewPayload?.amounts?.payable ?? preview.value?.amounts?.payable ?? 0)

    if (!Number.isFinite(payableAmount) || payableAmount <= 0) {
      return { success: false, message: '订单金额异常，请返回重新选择' }
    }

    const payload = buildOrderCreationPayload(payableAmount)

    try {
      const createRes = await fetch('http://localhost:8000/orders/hotel/create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      })
      const createData = await createRes.json()

      if (createData.code === 200 && createData.data?.order_no) {
        currentOrder.value.orderNo = createData.data.order_no
        currentOrder.value.status = createData.data.status ?? 'pending'
        if (route.query.order_no !== currentOrder.value.orderNo) {
          try {
            await router.replace({
              query: {
                ...route.query,
                order_no: currentOrder.value.orderNo
              }
            })
          } catch (navigationError) {
            console.warn('router.replace failed', navigationError)
          }
        }
        return { success: true }
      }

      return {
        success: false,
        message: createData.message || '创建订单失败，请稍后重试'
      }
    } catch (error) {
      console.error(error)
      return { success: false, message: '创建订单失败，请稍后重试' }
    }
  })()

  creatingOrderPromise = promise
  const result = await promise
  creatingOrderPromise = null
  return result
}

const fetchPreview = async () => {
  loading.value = true
  error.value = ''
  try {
    const res = await fetch('http://localhost:8000/orders/hotel/preview', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        hotel_id: queryParams.value.hotel_id,
        room_type_id: queryParams.value.room_type_id,
        check_in_date: queryParams.value.check_in_date,
        check_out_date: queryParams.value.check_out_date,
        rooms: queryParams.value.rooms
      })
    })
    const data = await res.json()
    if (data.code === 200) {
      const creationResult = await ensureOrderCreated(
        data.data,
        Number(data.data?.amounts?.payable ?? 0)
      )
      if (!creationResult.success) {
        error.value = creationResult.message || '创建订单失败，请稍后重试'
        return
      }
      preview.value = data.data
      initializeCountdown(data.data)
    } else {
      error.value = data.message || '试算失败'
    }
  } catch (e) {
    console.error(e)
    error.value = '网络错误，请稍后重试'
  } finally {
    loading.value = false
  }
}

const fetchOrderInfo = async () => {
  if (!currentOrder.value.orderNo) {
    error.value = '未找到订单信息'
    return
  }

  loading.value = true
  error.value = ''
  try {
    const res = await fetch(
      `http://localhost:8000/orders/hotel/payment-info?order_no=${encodeURIComponent(
        currentOrder.value.orderNo
      )}`
    )
    const data = await res.json()
    if (data.code === 200 && data.data) {
      preview.value = data.data
      initializeCountdown(data.data)
    } else {
      error.value = data.message || '获取订单信息失败'
    }
  } catch (e) {
    console.error(e)
    error.value = '网络错误，请稍后重试'
  } finally {
    loading.value = false
  }
}

const handleRetry = () => {
  if (hasPreviewParams.value) {
    fetchPreview()
  } else {
    fetchOrderInfo()
  }
}

const showModal = (message, title = '提示') => {
  modalMessage.value = message
  modalTitle.value = title
  modalVisible.value = true
}

const handleModalConfirm = () => {
  // 如果是成功提示或订单号提示，确认后跳转到订单列表
  if (modalMessage.value.includes('订单号') || modalMessage.value.includes('订单创建成功')) {
    router.push('/orders')
  }
}

const submitPayment = async () => {
  if (isCountdownExpired.value) {
    showModal('订单支付已超时，请重新选择房型重新下单', '提示')
    return
  }
  if (!preview.value) return

  loading.value = true
  try {
    const payableAmount = Number(preview.value.amounts?.payable || 0)
    if (!payableAmount) {
      showModal('订单金额异常，请返回重新选择', '错误')
      return
    }

    const creationResult = await ensureOrderCreated(preview.value, payableAmount)
    if (!creationResult.success) {
      showModal(creationResult.message || '创建订单失败，请稍后重试', '错误')
      return
    }

    if (selectedPayment.value === 'alipay') {
      const subject =
        preview.value?.hotel?.hotel_name
          ? `酒店订单 - ${preview.value.hotel.hotel_name}`
          : '酒店订单支付'

      const payRes = await fetch('http://localhost:8000/orders/hotel/pay', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          order_no: currentOrder.value.orderNo,
          amount: payableAmount,
          subject
        })
      })
      const payData = await payRes.json()

      if (payData.code === 200 && payData.data?.pay_url) {
        window.location.href = payData.data.pay_url
      } else {
        showModal(payData.message || '获取支付链接失败，请稍后重试', '错误')
      }
    } else if (selectedPayment.value === 'wechat') {
      // 微信支付仍在开发中，保留提示信息
      showModal(
        `微信支付功能开发中，请使用支付宝支付\n订单号：${currentOrder.value.orderNo}`,
        '提示'
      )
    }
  } catch (e) {
    console.error(e)
    showModal('网络错误，请稍后重试', '错误')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  if (hasPreviewParams.value) {
    fetchPreview()
    return
  }

  if (currentOrder.value.orderNo) {
    fetchOrderInfo()
  } else {
    error.value = '未找到订单信息'
  }
})

onUnmounted(() => {
  clearCountdown()
})
</script>

<template>
  <div class="payment-page">
    <header class="page-header">
      <div class="header-content">
        <button class="back-btn" @click="router.back()">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M15 18L9 12L15 6" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
        </button>
        <h1 class="page-title">选择支付方式</h1>
        <div class="header-placeholder"></div>
      </div>
    </header>

    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="error" class="error">
      <div>{{ error }}</div>
      <button class="retry-btn" @click="handleRetry">重试</button>
    </div>

    <div v-else-if="preview" class="content">
      <!-- 订单信息摘要 -->
      <section class="order-summary">
        <div class="summary-title">订单信息</div>
        <div class="hotel-info">
          <div class="hotel-name">{{ preview.hotel.hotel_name }}</div>
          <div class="room-info">{{ preview.room_type.name }}</div>
          <div class="stay-info">
            入住 {{ preview.stay.check_in_date }} · 退房 {{ preview.stay.check_out_date }} · 共 {{ preview.stay.nights }} 晚
          </div>
        </div>
        <div class="amount-info">
          <div class="amount-row">
            <span>应付金额</span>
            <span class="payable">¥{{ preview.amounts.payable.toFixed(2) }}</span>
          </div>
        </div>
        <div class="countdown-banner" :class="{ expired: isCountdownExpired }">
          <template v-if="!isCountdownExpired">
            请在 <span class="time">{{ countdownText }}</span> 内完成支付
          </template>
          <template v-else>
            支付已超时，请重新下单
          </template>
        </div>
      </section>

      <!-- 支付方式选择 -->
      <section class="payment-methods">
        <div class="card-title">选择支付方式</div>
        
        <div class="payment-item" :class="{ active: selectedPayment === 'alipay' }" @click="selectedPayment = 'alipay'">
          <div class="payment-icon alipay-icon">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M21.5 2.5H2.5V21.5H21.5V2.5Z" stroke="#1677FF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M7 12L10 15L17 8" stroke="#1677FF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
          <div class="payment-info">
            <div class="payment-name">支付宝</div>
            <div class="payment-desc">推荐使用</div>
          </div>
          <div class="payment-radio" :class="{ checked: selectedPayment === 'alipay' }">
            <div v-if="selectedPayment === 'alipay'" class="radio-dot"></div>
          </div>
        </div>

        <div class="payment-item" :class="{ active: selectedPayment === 'wechat' }" @click="selectedPayment = 'wechat'">
          <div class="payment-icon wechat-icon">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M21.5 2.5H2.5V21.5H21.5V2.5Z" stroke="#07C160" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              <path d="M7 12L10 15L17 8" stroke="#07C160" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
          <div class="payment-info">
            <div class="payment-name">微信支付</div>
            <div class="payment-desc">安全便捷</div>
          </div>
          <div class="payment-radio" :class="{ checked: selectedPayment === 'wechat' }">
            <div v-if="selectedPayment === 'wechat'" class="radio-dot"></div>
          </div>
        </div>
      </section>

      <!-- 提交按钮 -->
      <div class="submit-bar">
        <div class="payable-info">
          <span class="label">应付：</span>
          <span class="payable">¥{{ preview.amounts.payable.toFixed(2) }}</span>
        </div>
        <button class="submit-btn" @click="submitPayment" :disabled="loading || isCountdownExpired">
          {{ loading ? '处理中...' : '确认支付' }}
        </button>
      </div>
    </div>

    <Modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      :message="modalMessage"
      @confirm="handleModalConfirm"
    />
  </div>
</template>

<style scoped>
.payment-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.page-header {
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 375px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  height: 56px;
}

.back-btn {
  background: none;
  border: none;
  padding: 8px;
  cursor: pointer;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.header-placeholder {
  width: 36px;
}

.loading,
.error {
  padding: 40px 16px;
  text-align: center;
}

.retry-btn {
  margin-top: 12px;
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 8px 14px;
  cursor: pointer;
}

.content {
  max-width: 375px;
  margin: 0 auto;
  padding-bottom: 80px;
}

.order-summary {
  background: #fff;
  margin: 12px 12px 0;
  border-radius: 12px;
  padding: 16px;
}

.countdown-banner {
  margin-top: 14px;
  padding: 10px 12px;
  border-radius: 10px;
  background: #fff5eb;
  color: #ff6b35;
  font-size: 13px;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.countdown-banner .time {
  font-weight: 700;
  font-size: 15px;
}

.countdown-banner.expired {
  background: #fff1f0;
  color: #ff4d4f;
}

.summary-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.hotel-info {
  padding-bottom: 12px;
  border-bottom: 1px solid #f5f5f5;
  margin-bottom: 12px;
}

.hotel-name {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.room-info {
  font-size: 13px;
  color: #666;
  margin-bottom: 4px;
}

.stay-info {
  font-size: 12px;
  color: #999;
}

.amount-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  font-size: 14px;
  color: #333;
}

.payable {
  color: #ff6b35;
  font-weight: 700;
  font-size: 18px;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.payment-methods {
  background: #fff;
  margin: 12px;
  border-radius: 12px;
  padding: 16px;
}

.payment-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 2px solid #e8e8e8;
  border-radius: 12px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.payment-item:last-child {
  margin-bottom: 0;
}

.payment-item.active {
  border-color: #1890ff;
  background: #f0f7ff;
}

.payment-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
}

.alipay-icon {
  background: #e6f4ff;
}

.wechat-icon {
  background: #e6f7f0;
}

.payment-info {
  flex: 1;
}

.payment-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.payment-desc {
  font-size: 12px;
  color: #999;
}

.payment-radio {
  width: 20px;
  height: 20px;
  border: 2px solid #d9d9d9;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

.payment-radio.checked {
  border-color: #1890ff;
  background: #1890ff;
}

.radio-dot {
  width: 10px;
  height: 10px;
  background: #fff;
  border-radius: 50%;
}

.submit-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  border-top: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  max-width: 375px;
  margin: 0 auto;
}

.payable-info {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.payable-info .label {
  font-size: 14px;
  color: #666;
}

.payable-info .payable {
  font-size: 20px;
}

.submit-btn {
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-btn:hover:not(:disabled) {
  background: #40a9ff;
}

.submit-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}
</style>
